import Utils from './mod.utils';
import String from './mod.string';
import IndexDB from './mod.indexDB';
import Util from './util.js';

var nim = {};
//var nimAppKey = Util.nimAppKey;
var nimthis = null;
var Vuethis = null;
var mainVuethis = null;
var login_account = '';
var login_token = '';
var nim_debug = false;
var nim_autoMarkRead = true;
var onSyncDoneStatus = false;
var Nimdata = {};
var lastMsg = {};
var groupTidDel = {};
Nimdata.UsersObj = {};

let nimObj = {
  getNim: function () {
    return nim;
  },
  getSyncDoneStatus: function () {
    return onSyncDoneStatus;
  },
  setVuethis: function (_this) {
    Vuethis = _this;
  },
  getSessions: function () {
    var sessions = Nimdata.sessions || [];
    return sessions;
  },
  getMsgs: function () {
    var msgs = Nimdata.msgs || {};
    return msgs;
  },
  getNimdata: function () {
    return Nimdata;
  },
  setNimdata: function (data) {
    if (data) {
      Nimdata = data;
      this.indexedDB_add(); // 保存数据本地
    }
  },
  loginOutNimdata: function () {
    try {
      nim.disconnect();
    }
    catch (err) {

    }
    Nimdata = {
      sessions: [],
      msgs: {}
    };
  },
  getUsersObj: function () {
    return Nimdata.UsersObj;
  },
  setUsersObj: function (data) {
    if (data) {
      Nimdata.UsersObj = data;
      this.indexedDB_add(); // 保存数据本地
    }
  },
  getUsername: function (userid) {
    var UsersObj = Nimdata.UsersObj;
    var name = userid;
    if (UsersObj[userid] && UsersObj[userid].name != '') {
      name = UsersObj[userid].name;
    }
    return name;
  },
  getUserNoforid: function (userid) {
    var UsersObj = Nimdata.UsersObj;
    var no = userid;
    for (var k in UsersObj) {
      if (!UsersObj[k]) {
        continue;
      }
      var id = UsersObj[k].id;
      var no1 = UsersObj[k].no;
      if (id == userid) {
        no = no1;
        break;
      }
    }
    return no;
  },
  getUserImg: function (userid) {
    var UsersObj = Nimdata.UsersObj;
    var image = '';
    if (UsersObj[userid] && UsersObj[userid].image != '') {
      image = UsersObj[userid].image;
    }
    return image;
  },
  getNoToId: function (no) {
    var UsersObj = Nimdata.UsersObj;
    var id = '';
    if (UsersObj[no] && UsersObj[no].id != '') {
      id = UsersObj[no].id;
    }
    return id;
  },
  onUpdateChatList: function () {
    if (Vuethis) {
      Vuethis.getSessionData();
    }
  },
  onUpdateChatDetail: function (_data) {
    if (Vuethis && _data) {
      //Utils.fireEvent(Vuethis, Utils.kEvents.updateChatDetail, _data);
    }
  },
  indexedDB_add: function () {
    /*IndexDB.indexedDB_add(String.toJson(localStorage.getItem('userInfo')).username, 'Nimdata', String.toStr(Nimdata), function (res) {
     //console.log('保存数据：', res);
     });*/
  },
  onConnect: function (obj) {
    //console.log('connected:', obj);
  },
  onLoginPortsChange: function (ports) {
    console.log('登录状态改变:', ports);
  },
  onWillReconnect: function (obj) {
    console.log('重新连接: count = ' + obj.retryCount, obj);
  },
  onDisconnect: function (err) {
    console.log('断开连接，disconnect:', err);
    var cord = err.code; // logout 主动退出
    if (cord != 'logout') {
      if (mainVuethis) {

      }
      if (cord == '302') { // 密码错误
        var message = err.message;
        if (mainVuethis) {
          mainVuethis.$Message.destroy();
          mainVuethis.$Message.error(message);
        }
      } else if (cord == 'kicked') { // 不允许同一个帐号在多个地方同时登录
        if (mainVuethis) {
          mainVuethis.$Message.destroy();
          mainVuethis.$Message.error('您的账号在其他设备登录，请重新登录！<br>如非本人操作请修改密码！');
        }
      } else {
        if (mainVuethis) {
          // 重新连接
          nim.connect();
        }
      }

    }
  },
  onError: function (err) {
    console.log('error:', err);
  },
  onBlackList: function (list) {
    Nimdata.blacklist = Nimdata.blacklist || {};
    Nimdata.blacklist = nim.mergeRelations(Nimdata.blacklist, list);
    Nimdata.blacklist = nim.cutRelations(Nimdata.blacklist, list.invalid);
  },
  onSyncMarkInBlackList: function (obj) {
    if (obj.isAdd) {
      Nimdata.blacklist = nim.mergeRelations(Nimdata.blacklist, obj.record);
    } else {
      Nimdata.blacklist = nim.cutRelations(Nimdata.blacklist, obj.record);
    }

    //console.log('sync mark blacklist:', obj);
  },
  onMuteList: function (list) {
    Nimdata.mutelist = nim.mergeRelations(Nimdata.mutelist, list);
    Nimdata.mutelist = nim.cutRelations(Nimdata.mutelist, list.invalid);

    //console.log('mute list: ', Nimdata.mutelist);
  },
  onSyncMarkInMuteList: function (obj) {
    if (obj.isAdd) {
      Nimdata.mutelist = nim.mergeRelations(Nimdata.mutelist, obj);
    } else {
      Nimdata.mutelist = nim.cutRelations(Nimdata.mutelist, obj.invalid);
    }

    //console.log('sync mark mute: ', obj);
  },
  onFriends: function (friends) {
    Nimdata.friends = nim.mergeFriends(Nimdata.friends, friends);
    Nimdata.friends = nim.cutFriends(Nimdata.friends, friends.invalid);

    //console.log('friends: ', Nimdata.friends);
  },
  onSyncFriendAction: function (obj) {
    //console.log('sync friend action: ', obj);
  },
  onMyInfo: function (info) {
    Nimdata.myInfo = info;
    //console.log('my info: ', info);
  },
  onUpdateMyInfo: function (info) {
    Nimdata.myInfo = nim.util.merge(Nimdata.myInfo, info);
    //console.log('update my info: ', Nimdata.myInfo);
  },
  onUsers: function (user) {
    Nimdata.users = nim.mergeUsers(Nimdata.users, user);
    //console.log('users: ', Nimdata.users);
  },
  onUpdateUser: function (user) {
    Nimdata.users = nim.mergeUsers(Nimdata.users, user);
    //console.log('update users: ', Nimdata.users);
  },
  onRobots: function (robots) {
    Nimdata.robots = robots;
    //console.log('robots: ', robots);
  },
  onSessions: function (sessions) {
    console.log('初始化sessions', sessions);
    Nimdata.sessions = nim.mergeSessions(Nimdata.sessions, sessions);
    console.log('合并本地sessions', Nimdata.sessions);

    nimthis.indexedDB_add(); // 保存数据本地

    if (Vuethis) {
      Vuethis.getSessionData();
    }
    var sessions = Nimdata.sessions;
    for (var k in sessions) {
      if (!sessions[k]) {
        continue;
      }
      var sid = sessions[k].id;
      var unread = sessions[k].unread || 0;
      var sidArr = sid.split('-');
      var scene = sidArr[0] ? sidArr[0] : '';
      var toAccount = sidArr[1] ? sidArr[1] : '';
      // 有未读消息的，获取云端历史记录
      // if (unread > 0 && (scene == 'p2p' || scene == 'team')) {
      nimthis.getHistoryMsgsFun(scene, toAccount);
      // }
    }
  },
  onUpdateSession: function (session) {
    console.log('更新session', session);
    var isleaveTeam = false;
    if (session.lastMsg && session.lastMsg.from) {
      var username = String.toJson(localStorage.getItem('userInfo')).username;
      var form = session.lastMsg.from;
      var scene = session.lastMsg.scene;
      var type = session.lastMsg.type;
      var id = session.id;
      var arr = id.split('-');
      var tid = arr[1];
      if (type == 'notification' && scene == 'team' && username == form) {
        var attach = session.lastMsg.attach;
        var attachtype = attach.type;
        if (attachtype == 'leaveTeam') {// 我退出群了
          isleaveTeam = true;
          // 删除本地.Nimdata.sessions
          for (var i = 0; i < Nimdata.sessions.length; i++) {
            var sid = Nimdata.sessions[i].id;
            if (id == sid) {
              var del = Nimdata.sessions.splice(i, 1);
              nimthis.nim_delsessions('team', tid);// 删除群会话
              break;
            }
          }
        }
      }
    }
    if (isleaveTeam == false) {
      Nimdata.sessions = nim.mergeSessions(Nimdata.sessions, session);
    }
    nimthis.indexedDB_add(); // 保存数据本地

    var sessionId = session.id;
    var _data = {
      sid: sessionId,
      page: 'no',
    };
    if (Vuethis) {
      if (sessionId == Vuethis.sid) {
        //_data.page = 'open';
      }
      Vuethis.getSessionData();
      Vuethis.onUpdateMsgList(_data);
    }

  },
  onRoamingMsgs: function (obj) {
    console.log('-------------->>> Roaming >', obj);
    nimthis.pushMsg(obj.msgs);
  },
  onOfflineMsgs: function (obj) {
    console.log('-------------->>> Offline >', obj);
    nimthis.pushMsg(obj.msgs);
  },
  onMsg: function (msg) {
    console.log('>>> Msg >', msg.scene, msg.type, msg);
    var notPush = false;
    var type = msg.type;
    var scene = msg.scene;
    var sessionId = msg.sessionId;
    if (scene == 'team' && type == 'notification') { // 通知
      var attach = msg.attach;
      var atype = attach.type;
      var arr = sessionId.split('-');
      var tid = arr[1];
      if (atype == 'dismissTeam') {// 群被解散了
        nimthis.nim_delsessions('team', tid);// 删除群会话
        if (Vuethis && Vuethis != null) {
          Vuethis.clear();
        }
      } else if (atype == 'removeTeamMembers') {//删除成员
        var accounts = attach.accounts;//成员数组userid
        var userid = String.toJson(localStorage.getItem('userInfo')).username;
        for (var k in accounts) {
          var kid = accounts[k];
          if (kid == userid) {// 自己被踢出了
            nimthis.nim_delsessions('team', tid);// 删除群会话
            if (Vuethis && Vuethis != null) {
              Vuethis.clear();
            }
          }
        }
      } else if (atype == 'leaveTeam') {//自己退群
        var users = attach.users;//成员数组
        if (users[0]) {
          var account = users[0].account;
          var userid = String.toJson(localStorage.getItem('userInfo')).username;
          if (account == userid) {
            notPush = true;
          }
        }
      } else if (atype == 'addTeamMembers') {//自己加新群了
        var users = attach.accounts;//成员数组
        if (users[0]) {
          var account = users[0];
          var userid = String.toJson(localStorage.getItem('userInfo')).username;
          if (account == userid) {

          }
        }
      }
    }

    lastMsg = msg;
    if (notPush != true) {
      nimthis.pushMsg(msg);
    }

    var _data = {
      sid: sessionId,
      page: 'no',
    };
    if (Vuethis && Vuethis != null) {
      Vuethis.onUpdateMsgList(_data);
    } else {
      console.log('Vuethis 无效');
    }
  },
  pushMsg: function (msgs) {
    if (!Array.isArray(msgs)) {
      msgs = [msgs];
    }
    var sid = msgs[0].sessionId;
    Nimdata.msgs = Nimdata.msgs || {};
    Nimdata.msgs[sid] = nim.mergeMsgs(Nimdata.msgs[sid], msgs);

    nimthis.indexedDB_add(); // 保存数据本地
    //console.log('merged msg', Nimdata.msgs);

  },
  sendMsgReceiptDone: function (err, obj) {
    if (err) {
      //console.log('msg receipt done err', err);
    }

    //console.log('已读回执，receipt:', obj);
  },
  // 获取云端历史记录
  getHistoryMsgsFun: function (scene, to, fun, lastMsg) {

    function getHistoryMsgsDone(error, obj) {
      console.log('获取历史消息:' + scene + '-' + to + '>>' + (!error ? '成功' : '失败'), obj);
      if (!error) {
        // console.log(obj.msgs);
        var msgs = obj.msgs;
        if (msgs && msgs.length > 0) {
          nimthis.pushMsg(msgs);
        }
        if (fun) {
          fun(msgs);
        }
      }
    }

    var lastMsgId = '';
    var endTime = '';
    if (lastMsg) {
      lastMsgId = lastMsg.idServer;
      endTime = lastMsg.time;
      nim.getHistoryMsgs({
        scene: scene,
        to: to,
        endTime: endTime,
        lastMsgId: lastMsgId,
        reverse: false,
        done: getHistoryMsgsDone
      });
    } else {
      nim.getHistoryMsgs({
        scene: scene,
        to: to,
        reverse: false,
        done: getHistoryMsgsDone
      });
    }
  },
  // 插入一条本地会话记录
  insertLocalSession: function (scene, to, fun, updateTime) {
    nim.insertLocalSession({
      scene: scene,
      to: to,
      updateTime: updateTime,
      done: insertLocalSessionDone
    });
    function insertLocalSessionDone(error, obj) {
      console.log('插入本地会话记录' + (!error ? '成功' : '失败'), error, obj);
      if (!error) {
        nimthis.onSessions(obj.session);
        if (fun) {
          fun(obj.session);
        }
      }
    }
  },
  onBroadcastMsg: function (msg) {
    //console.log('broadcast msg', msg.scene, msg.type, msg);
  },
  onBroadcastMsgs: function (msgs) {
    //console.log('broadcase msgs', msgs.size, msgs);
  },
  onOfflineSysMsgs: function (sysMsgs) {
    //console.log('>>> Offline Sys >', sysMsgs.size, sysMsgs);
    for (var s = 0; s < sysMsgs.length; s++) {
      var sysMsg = sysMsgs[s];
      if (sysMsg && sysMsg.msg && sysMsg.msg.time) { // 撤回消息
        var deltime = sysMsg.msg.time;
        var sessionId = sysMsg.msg.sessionId;
        var leng = Nimdata.msgs[sessionId].length;
        for (var i = leng - 1; i >= 0; i--) {
          var time = Nimdata.msgs[sessionId][i].time;
          if (deltime == time) {
            var del = Nimdata.msgs[sessionId].splice(i, 1);
            nimthis.indexedDB_add(); // 保存数据本地
            var _data = {
              sid: sessionId,
              page: 'no',
            };
            if (Vuethis) {
              Vuethis.getSessionData();
              Vuethis.onUpdateMsgList(_data);
            }
            return false;
          }
        }
      }
    }
    nimthis.pushSysMsgs(sysMsgs);
  },
  onSysMsg: function (sysMsg) {
    //console.log('>>> Sys Msg >', sysMsg.scene, sysMsg.type, sysMsg);
    if (sysMsg.msg && sysMsg.msg.time) {// 撤回消息
      var deltime = sysMsg.msg.time;
      var sessionId = sysMsg.msg.sessionId;
      var leng = Nimdata.msgs[sessionId].length;
      for (var i = leng - 1; i >= 0; i--) {
        var time = Nimdata.msgs[sessionId][i].time;
        if (deltime == time) {
          var del = Nimdata.msgs[sessionId].splice(i, 1);
          nimthis.indexedDB_add(); // 保存数据本地
          var _data = {
            sid: sessionId,
            page: 'no',
          };
          if (Vuethis) {
            Vuethis.getSessionData();
            Vuethis.onUpdateMsgList(_data);
          }
          return false;
        }
      }
    }
    nimthis.pushSysMsgs(sysMsg);
  },
  onUpdateSysMsg: function (msg) {
    //console.log('update sys Msg', msg.scene, msg.type, msg);
    nimthis.pushSysMsgs(msg)
  },
  pushSysMsgs: function (msgs) {
    Nimdata.sysMsgs = nim.mergeSysMsgs(Nimdata.sysMsgs, msgs);
    //console.log('push sys msgs:', msgs.size, msgs);
  },
  onSysMsgUnread: function (msg) {
    Nimdata.sysMsgUnread = msg;
    //console.log('系统通知未读数', msg);
  },
  onUpdateSysMsgUnread: function (msg) {
    Nimdata.sysMsgUnread = msg;
    //console.log('系统通知未读数更新了', msg);
  },
  onOfflineCustomSysMsgs: function (msgs) {
    console.log('离线自定义系统通知:', msgs.size, msgs);
    //反转
    msgs.reverse();
    var have_msg = false;
    for (var k in msgs) {
      var type = msgs[k].type;
      var content = msgs[k].content;
      var from = msgs[k].from;
      var idServer = msgs[k].idServer;
      var scene = msgs[k].scene;
      var sendToOnlineUsersOnly = msgs[k].sendToOnlineUsersOnly;
      var status = msgs[k].status;
      var time = msgs[k].time;
      var to = msgs[k].to;

      var contentObj = String.toJson(content);
      if (contentObj && contentObj.system) {// 系统通知
        var systemObj = contentObj.system;
        var ctype = systemObj.type;
        var cvalue = systemObj.data.value;
        var title = systemObj.data.title;
        var systemStr = String.toStr(systemObj);

        var obj = {
          id: 'sys-' + ctype,
          scene: scene,
          type: type,
          to: to,
          unread: 0,
          updateTime: time,
          lastMsg: {
            text: title
          },
        };
        Nimdata.sessions = nim.mergeSessions(Nimdata.sessions, obj);

        var misObj = {
          cc: true,
          flow: "in",
          from: from,
          fromClientType: "Web",
          fromDeviceId: idServer,
          fromNick: '',
          idClient: idServer,
          idServer: idServer,
          isHistoryable: true,
          isLocal: false,
          isOfflinable: true,
          isPushable: true,
          isRoamingable: true,
          isSyncable: true,
          isUnreadable: true,
          needPushNick: true,
          resend: false,
          scene: "p2p",
          sessionId: 'sys-' + ctype,
          status: "success",
          target: time,
          text: cvalue,
          content: systemStr,
          time: time,
          to: to,
          type: "custom",
          userUpdateTime: time
        };
        lastMsg = misObj;
        nimthis.pushMsg(misObj);
        have_msg = true;
      } else if (contentObj && contentObj.type && contentObj.type == 'push') {//推送消息
        var pushData = contentObj.data ? contentObj.data : {};
        var from_id = pushData.from_id;
        var from = pushData.from;
        var title = pushData.title;
        var type = pushData.type;
        var content = pushData.content;
        content = content.replace(/,点击查看/g, '');

        var contentStr = String.toStr(contentObj);
        var misObj = {
          cc: true,
          flow: "in",
          from: from,
          fromClientType: "Web",
          fromDeviceId: idServer,
          fromNick: '',
          idClient: idServer,
          idServer: idServer,
          isHistoryable: true,
          isLocal: false,
          isOfflinable: true,
          isPushable: true,
          isRoamingable: true,
          isSyncable: true,
          isUnreadable: true,
          needPushNick: true,
          resend: false,
          reading: false,
          scene: "p2p",
          sessionId: 'push-msg',
          status: "success",
          target: time,
          text: content,
          content: contentStr,
          time: time,
          to: to,
          type: "custom",
          userUpdateTime: time
        };
        nimthis.pushMsg(misObj);
      }
    }
    if (msgs.length > 0 && have_msg == true) {
      // 保存到本地数据库
      if (Vuethis) {
        Vuethis.getSessionData();
      }
    }

  },
  onCustomSysMsg: function (msg) {
    var _this = this;
    console.log('收到自定义系统通知:', msg.scene, msg.type, msg);
    var type = msg.type;
    var content = msg.content;
    var from = msg.from;
    var idServer = msg.idServer;
    var scene = msg.scene;
    var sendToOnlineUsersOnly = msg.sendToOnlineUsersOnly;
    var status = msg.status;
    var time = msg.time;
    var to = msg.to;

    var contentObj = String.toJson(content);

    if (contentObj && contentObj.system) {// 系统通知
      var systemObj = contentObj.system;
      var ctype = systemObj.type;
      var cvalue = systemObj.data.value;
      var title = systemObj.data.title;
      var systemStr = String.toStr(systemObj);

      var obj = {
        id: 'sys-' + ctype,
        scene: scene,
        type: type,
        to: to,
        unread: 0,
        updateTime: time,
        lastMsg: {
          text: title
        },
      };
      Nimdata.sessions = nim.mergeSessions(Nimdata.sessions, obj);

      var misObj = {
        cc: true,
        flow: "in",
        from: from,
        fromClientType: "Web",
        fromDeviceId: idServer,
        fromNick: '',
        idClient: idServer,
        idServer: idServer,
        isHistoryable: true,
        isLocal: false,
        isOfflinable: true,
        isPushable: true,
        isRoamingable: true,
        isSyncable: true,
        isUnreadable: true,
        needPushNick: true,
        resend: false,
        scene: "p2p",
        sessionId: 'sys-' + ctype,
        status: "success",
        target: time,
        text: cvalue,
        content: systemStr,
        time: time,
        to: to,
        type: "custom",
        userUpdateTime: time
      };
      lastMsg = misObj;
      nimthis.pushMsg(misObj);

      if (Vuethis) {
        Vuethis.getSessionData();
      }
    } else if (contentObj && contentObj.type && contentObj.type == 'push') {//推送消息
      var pushData = contentObj.data ? contentObj.data : {};
      var from_id = pushData.from_id;
      var from = pushData.from;
      var title = pushData.title;
      var type = pushData.type;
      var content = pushData.content;
      content = content.replace(/,点击查看/g, '');

      var contentStr = String.toStr(contentObj);
      var misObj = {
        cc: true,
        flow: "in",
        from: from,
        fromClientType: "Web",
        fromDeviceId: idServer,
        fromNick: '',
        idClient: idServer,
        idServer: idServer,
        isHistoryable: true,
        isLocal: false,
        isOfflinable: true,
        isPushable: true,
        isRoamingable: true,
        isSyncable: true,
        isUnreadable: true,
        needPushNick: true,
        resend: false,
        reading: false,
        scene: "p2p",
        sessionId: 'push-msg',
        status: "success",
        target: time,
        text: content,
        content: contentStr,
        time: time,
        to: to,
        type: "custom",
        userUpdateTime: time
      };
      nimthis.setLocalMessage(misObj);

      var name = new Date().getTime() + '_' + Utils.getRandom();
      if (mainVuethis) {
        function onCloseFun(nameid, msg) {
          mainVuethis.$Notice.close(nameid);

          sessionStorage.setItem('from_id', from_id);

          switch (from) {
            case 'task' ://任务
              mainVuethis.$router.push({
                name: 'task_index'
              });
              break;
            case 'journal' ://日志
              sessionStorage.setItem('journal_title', title);
              sessionStorage.removeItem('from_id');
              mainVuethis.$router.push({
                name: 'logs_index'
              });
              break;
            case 'approval' ://审批
              localStorage.setItem('approval_type', 'approving');//待我审批的
              mainVuethis.$router.push({
                name: 'approval_index'
              });
              break;
            case 'announcement' :// 公告
              mainVuethis.$router.push({
                name: 'affiche_index'
              });
              break;
            case 'meeting' :// 会议
              mainVuethis.$router.push({
                name: 'meeting'
              });
              break;
            case 'clock' :// 签到
              sessionStorage.removeItem('from_id');
              mainVuethis.$router.push({
                name: 'clock_today'
              });
              break;
            case 'retire' :// 退休
              mainVuethis.$router.push({
                name: 'user_retired'
              });
              break;
            case 'email' :// 微邮
              mainVuethis.$router.push({
                name: 'email_index'
              });
              break;
            case 'feedback' :// 意见反馈
              mainVuethis.$router.push({
                name: 'feedback_add'
              });
              break;
            default :
              sessionStorage.removeItem('from_id');
              break;
          }
          nimthis.get_all_reading();
        }

        mainVuethis.$Notice.info({
          title: title,
          desc: content,
          duration: 5,
          name: name,//当前通知的唯一标识
          //onClose: onCloseFun,//关闭时回调
          render: h => {
            return h('span', [
              h('div', {
                style: {
                  cursor: 'pointer'
                },
                on: {
                  click: e => {
                    e.stopPropagation();
                    onCloseFun(name, misObj);
                  }
                }
              }, content),
            ])
          }
        });
        nimthis.get_all_reading();
      }
    }

  },
  // 保存推送消息
  setLocalMessage: function (msg) {
    var localMessage = Nimdata.localMessage || [];
    var have = false;
    for (var k in localMessage) {
      if (!localMessage[k]) {
        continue;
      }
      if (localMessage[k].idServer == msg.idServer) { // 已存在
        have = true;
        localMessage[k] = msg;
        break;
      }
    }
    if (have == false) { // 不存在的
      localMessage.push(msg);
    }
    Nimdata.localMessage = localMessage;
    nimthis.indexedDB_add(); // 保存数据本地
  },
  // 全部标记为已读
  setLocalMessage_reading_all: function () {
    var localMessage = Nimdata.localMessage || [];
    for (var k in localMessage) {
      if (!localMessage[k]) {
        continue;
      }
      localMessage[k].reading = true; // 已读
    }
    Nimdata.localMessage = localMessage;
    nimthis.indexedDB_add(); // 保存数据本地
  },
  get_all_reading: function () {
    var _this = this;
    Utils.localMessage_reading_fun(function (res) {
      var unread = 0;
      if (res.result == 0) {
        if (res.unread && res.unread > 0) {
          unread = res.unread;
        }
      }
      mainVuethis.$store.state.app.localMessage_unread = unread;
    });
  },
  onTeams: function (teams) {
    Nimdata.teams = nim.mergeTeams(Nimdata.teams, teams);
    Nimdata.teams = nim.cutTeams(Nimdata.teams, teams);
    Nimdata.invalidTeams = nim.mergeTeams(Nimdata.invalidTeams, teams);
  },
  onSyncCreateTeam: function (team) {
    Nimdata.teams = nim.mergeTeams(Nimdata.teams, team);


    // 保存到本地数据库
  },
  onTeamMembers: function (obj) {
    var teamId = obj.teamId;
    var members = obj.members;

    Nimdata.teamMembers = Nimdata.teamMembers || {};
    Nimdata.teamMembers[teamId] = nim.mergeTeamMembers(Nimdata.teamMembers[teamId],
      members);
    Nimdata.teamMembers[teamId] = nim.cutTeamMembers(Nimdata.teamMembers[teamId],
      members.invalid);

    //console.log('team members', obj);
  },
  onSyncTeamMembersDone: function () {
    //console.log('sync team members done');
  },
  onUpdateTeamMember: function (teamMember) {
    nimthis.onTeamMembers({
      teamId: teamMember.teamId,
      members: teamMember
    });

    //console.log('update team member:', teamMember);
  },
  onSyncDone: function () {
    onSyncDoneStatus = true;
    console.log('同步完毕');
  },
  nim_no_login: function (vue_this, account, token) {
    nimthis = this;
    mainVuethis = vue_this;
  },
  nim_login: function (vue_this, account, token) {
    nimthis = this;
    mainVuethis = vue_this;
    login_account = account;
    login_token = token;
    nim = SDK.NIM.getInstance({
      debug: nim_debug,//是否开启日志, 开发者可以开启日志
      autoMarkRead: nim_autoMarkRead,//对收到的消息，是否自动标记为已读
      syncMsgReceipts: true,//同步消息已读回执
      syncSessionUnread: true,//是否同步会话未读数(开启数据库时有效，保证多端未读数相一致)

      appKey: Util.nimAppKey,//在云信管理后台查看应用的 appKey
      account: account,//帐号, 应用内唯一
      token: token,//帐号的 token, 用于建立连接

      onconnect: nimthis.onConnect,//连接建立后的回调(登录成功), 会传入一个对象, 包含登录的信息
      onerror: nimthis.onError,//发生错误的回调, 会传入错误对象
      onwillreconnect: nimthis.onWillReconnect,//即将重连的回调
      ondisconnect: nimthis.onDisconnect,//断开连接后的回调
      onloginportschange: nimthis.onLoginPortsChange,//当前登录帐号在其它端的状态发生改变了

      onmyinfo: nimthis.onMyInfo,//我的名片, 对应回调

      onblacklist: nimthis.onBlackList,//黑名单, 对应回调
      onmutelist: nimthis.onMuteList,//静音列表, 对应回调
      onfriends: nimthis.onFriends,//好友, 对应回调
      onusers: nimthis.onUsers,//好友的名片, 对应回调
      onrobots: nimthis.onRobots,//机器人列表的回调
      onteams: nimthis.onTeams,//群列表, 对应回调

      onsessions: nimthis.onSessions,//收到会话列表, 对应回调
      onroamingmsgs: nimthis.onRoamingMsgs,//漫游消息, 对应回调
      onofflinemsgs: nimthis.onOfflineMsgs,//离线消息, 对应回调
      // onofflinefiltermsgs

      // onroamingsysmsgs
      onofflinesysmsgs: nimthis.onOfflineSysMsgs,//离线系统通知, 对应回调
      // onofflinefiltersysmsgs
      onofflinecustomsysmsgs: nimthis.onOfflineCustomSysMsgs,//离线自定义系统通知, 对应回调
      // onofflinefiltercustomsysmsgs

      onbroadcastmsg: nimthis.onBroadcastMsg,//收到广播消息
      onbroadcastmsgs: nimthis.onBroadcastMsgs,//收到广播消息列表

      onsysmsgunread: nimthis.onSysMsgUnread,//收到系统通知未读数
      onsyncdone: nimthis.onSyncDone,//数据同步完成

      onteammembers: nimthis.onTeamMembers,//群成员信息更新
      onsyncteammembersdone: nimthis.onSyncTeamMembersDone,//同步群列表完成

      onmsg: nimthis.onMsg,//收到消息
      onsysmsg: nimthis.onSysMsg,//收到系统通知
      oncustomsysmsg: nimthis.onCustomSysMsg,//收到自定义系统通知

      onupdatemyinfo: nimthis.onUpdateMyInfo,//我的名片更新了
      onupdateuser: nimthis.onUpdateUser,//用户名片更新了
      onupdateteammember: nimthis.onUpdateTeamMember,//群成员信息更新了

      // onCreateTeam
      // onUpdateTeam
      // onAddTeamMembers
      // onRemoveTeamMembers
      // onUpdateTeamManagers
      // onDismissTeam
      // onTransferTeam
      // onUpdateTeamMembersMute

      onupdatesession: nimthis.onUpdateSession,//会话更新了
      onupdatesysmsgunread: nimthis.onUpdateSysMsgUnread,//系统通知未读数更新了
      onupdatesysmsg: nimthis.onUpdateSysMsg,//

      onsynccreateteam: nimthis.onSyncCreateTeam,//你创建了一个群
      onsyncmarkinblacklist: nimthis.onSyncMarkInBlackList,////console.log(obj.account + '被你在其它端' + (obj.isAdd ? '加入' : '移除') + '黑名单');
      onsyncmarkinmutelist: nimthis.onSyncMarkInMuteList,////console.log(obj.account + '被你' + (obj.isAdd ? '加入' : '移除') + '静音列表');
      onsyncfriendaction: nimthis.onSyncFriendAction,//加、申请、通过、拒绝、删除、更新了一个好友

      // shouldIgnoreNotification
      // shouldCountNotifyUnread
      // onPushNotificationMultiportConfig
      // onPushNotificationMultiportConfigUpdate
      // onpushevents
    });
  },
  send: function (scene, to, text) {
    var msg = nim.sendText({
      scene: scene,
      to: to,
      text: text,
      done: this.sendMsgDone
    });

    lastMsg = msg;

    //console.log('send text: ', msg);
  },
  sendCustom: function (scene, to, obj) {
    var msg = nim.sendCustomMsg({
      scene: scene,
      to: to,
      content: JSON.stringify(obj),
      done: this.sendMsgDone
    });

    lastMsg = msg;
    //console.log('send custom: ', msg);
  },
  forwardMsg: function (scene, to, someMsg) {
    nim.forwardMsg({
      msg: someMsg,
      scene: scene,
      to: to,
      done: this.sendMsgDone
    })
  },
  sendMsgDone: function (err, msg) {
    if (err) {

    } else {
      lastMsg = msg;
      nimthis.pushMsg(msg);
    }
  },
  getLocal: function (sessionId, fun) {
    nim.getLocalMsgs({
      sessionId: sessionId,
      limit: 100,
      done: getLocalMsgDone
    });
    function getLocalMsgDone(err, obj) {
      console.log('getLocalMsgDone', err, obj, sessionId);
      if (err) {
        //console.log('get local msg err', err);
      } else {
        //console.log('get local msg done', obj);
        var sid = sessionId;
        Nimdata.msgs = Nimdata.msgs || {};
        Nimdata.msgs[sid] = nim.mergeMsgs(Nimdata.msgs[sid], obj.msgs);
        nimthis.indexedDB_add(); // 保存数据本地
        if (fun) {
          fun(Nimdata.msgs);
        }
      }
    }
  },
  getLocalMsgDone: function (err, obj) {
    if (err) {
      //console.log('get local msg err', err);
    } else {
      //console.log('get local msg done', obj);
    }
  },
  // 删除会话
  nim_delsessions: function (scene, toid, update) {
    var sid = scene + '-' + toid;
    groupTidDel[sid] = sid;
    nimthis.deleteLocalMsgsBySession(scene, toid);//删除消息
    nim.deleteLocalSession({
      id: sid,
      done: deleteLocalSessionDone
    });
    function deleteLocalSessionDone(error, obj) {
      console.log('删除本地会话' + (!error ? '成功' : '失败'), obj, error);
    }

    nim.deleteSession({
      scene: scene,
      to: toid,
      done: deleteSessionDone
    });
    function delsetTimeout(delid) {
      if (groupTidDel[delid]) {
        delete groupTidDel[delid];
      }
    }

    function deleteSessionDone(error, obj) {
      console.log('删除服务器上的会话' + (!error ? '成功' : '失败'), obj, error);
      setTimeout(function () {
        delsetTimeout(sid)
      }, 5000);
    }

    // 删除本地_nimthis.Nimdata.sessions
    for (var i = 0; i < Nimdata.sessions.length; i++) {
      var sid = Nimdata.sessions[i].id;
      if (groupTidDel[sid]) {
        var del = Nimdata.sessions.splice(i, 1);
        break;
      }
    }
    nimthis.indexedDB_add(); // 保存数据本地
    if (Vuethis) {
      Vuethis.getSessionData();
    }

  },
  // 删除聊天记录
  deleteLocalMsgsBySession: function (scene, to) {
    var sid = scene + '-' + to;
    Nimdata.msgs[sid] = [];
    nimthis.indexedDB_add(); // 保存数据本地
    // 网易云信删除某个会话的本地消息
    nim.deleteLocalMsgsBySession({
      scene: scene,
      to: to,
      done: deleteLocalMsgsBySession
    });

    function deleteLocalMsgsBySession(error, obj) {
      console.log('删除会话本地消息' + (!error ? '成功' : '失败'));
    }
  },
  /**
   * 消息已读回执
   * */
  resetSessionUnread: function (sid, lastMsg) {
    function _sendMsgReceiptDone(err, obj) {
      if (err) {
        console.log('已读回执 err', err);
      }
      console.log('已读回执 obj:', obj);
    }

    // 标记为已读
    nim.resetSessionUnread(sid);
    // 已读回执
    nim.sendMsgReceipt({
      msg: lastMsg,
      done: _sendMsgReceiptDone
    });
  },
  /**
   * 发送通知消息
   * type 为通知的类型，公告：gonggao
   * id 为通知的id
   * title 标题
   * value 内容
   * scene p2p/team,暂定为p2p
   * account 发送目标账号
   * */
  // Nim_sendCustomSysMsg('gonggao', 'id12344', '标题3','测试系统通知3','p2p','13345114507');
  Nim_sendCustomSysMsg: function (type, id, title, value, scene, account) {
    var content = {
      type: type,
      data: {
        title: title,
        value: value,
        img: 'https://sd.jnaw.top/images/logo1.png',
        id: id
      }
    };
    content = JSON.stringify({system: content});
    var msgId = nim.sendCustomSysMsg({
      scene: scene,//'p2p',
      to: account,
      content: content,
      sendToOnlineUsersOnly: false,
      apnsText: content,
      done: _sendCustomSysMsgDone
    });

    function _sendCustomSysMsgDone(error, msg) {
      console.log('发送' + msg.scene + '自定义系统通知' + (!error ? '成功' : '失败'), msg, error);
    }
  },
  // 上传文件
  previewFile: function (fileInput, sid, scene) {
    // 参数type指定了要发送的文件类型, 包括图片、音频、视频和普通文件,
    // 对应的值分别为'image'、'audio'、'video'和'file', 不传默认为'file'。
    var type = 'file';
    nim.previewFile({
      type: type,
      fileInput: fileInput,
      uploadprogress: function (obj) {
        //console.log('文件总大小: ' + obj.total + 'bytes');
        //console.log('已经上传的大小: ' + obj.loaded + 'bytes');
        //console.log('上传进度: ' + obj.percentage);
        //console.log('上传进度文本: ' + obj.percentageText);
      },
      done: function (error, file) {
        //console.log('上传image' + (!error?'成功':'失败'));
        // show file to the user
        if (!error) {
          var arr = sid.split('-');
          if (arr[1]) {
            var to = arr[1];
            var msg = nim.sendFile({
              scene: scene,
              to: to,
              file: file,
              done: sendMsgDone
            });
            //console.log('正在发送p2p file消息, id=' + msg.idClient);
            nimthis.pushMsg(msg);
          }

        } else {
          Nimdata.isSend = false; // 发送完毕
          //console.log(error);
        }
      }
    });
  },
  sendMsgReceipt: function (msg) {
    //发送已读回执
    nim.sendMsgReceipt({
      msg: msg,
      done: sendMsgReceiptDone
    });
    function sendMsgReceiptDone(err, obj) {
      if (err) {
        console.log('已读回执 err', err);
      }
      console.log('已读回执 obj:', obj);
    }
  },


};
export default nimObj;
